package com.totoro.tyrank.manager;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.StaticSystemVarConst;
import com.totoro.tyrank.data.RankData;
import com.totoro.tyrank.mapper.RankDataMapper;
import com.totoro.tyrank.mapper.impl.RankDataMapperImpl;
import com.totoro.tyrank.utils.ColorUtil;
import com.totoro.tyrank.utils.DateUtil;
import lombok.Getter;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 排行榜持久化数据的管理器
 */
public class RankDataManager {

    private final Plugin plugin;

    @Getter
    private final Map<String, RankData> rankDataMap;

    private final RankDataMapper rankDataMapper = new RankDataMapperImpl();

    private static final File RANK_DATE_FILE = new File(TyRank.getInstance().getDataFolder().getPath() +
            StaticSystemVarConst.FILE_SEPARATOR + StaticSystemVarConst.RANK_DATA_DEFAULT_NAME);

    public RankDataManager(Plugin plugin) {
        this.plugin = plugin;
        this.rankDataMap = new HashMap<>();
    }

    public void saveRankData(List<RankData> rankDataList) {
        if(TyRank.getConfigManager().getConfigData().getMySQLData().getEnable()) {
            for (RankData rankData : rankDataList) {
                if (rankDataMapper.selectIsHaveRankByRankId(rankData.getRankId())) {
                    rankDataMapper.updateRankData(rankData);
                } else {
                    rankDataMapper.insertRankData(rankData);
                }
            }
        } else {
            YamlConfiguration rankDataConfig = getRankDataConfig();
            for (RankData rankData : rankDataList) {
                YamlConfiguration rankDataSection = new YamlConfiguration();
                rankDataSection.set("rank-id", rankData.getRankId());
                rankDataSection.set("is-end", rankData.getIsEnd());
                rankDataSection.set("update-date-time", rankData.getUpdateDateTime().format(StaticSystemVarConst.DATE_FORMATTER));
                rankDataConfig.set(rankData.getRankId(), rankDataSection);
            }
            try {
                rankDataConfig.save(RANK_DATE_FILE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void loadRankData() {
        // 加载所有配置...
        rankDataMap.clear();
        Set<String> rankIdsSet;
        if(TyRank.getConfigManager().getConfigData().getMySQLData().getEnable()) {
            rankIdsSet = rankDataMapper.selectAllRankData().stream().map(RankData::getRankId).collect(Collectors.toSet());
        } else {
            YamlConfiguration rankDataConfig = getRankDataConfig();
            rankIdsSet = rankDataConfig.getKeys(false);
        }
        for (String rankId : rankIdsSet) {
            loadRankData(rankId);
        }
    }

    public void loadRankData(String rankId) {
        RankData rankData;
        if(TyRank.getConfigManager().getConfigData().getMySQLData().getEnable()) {
            RankData byRankId = rankDataMapper.selectRankDataByRankId(rankId);
            if(null == byRankId) {
                plugin.getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                        ColorUtil.color(String.format("&c加载排行榜持久化数据失败：%s", rankId)));
                return;
            }
            rankData = byRankId;
        } else {
            YamlConfiguration rankDataConfig = getRankDataConfig();
            ConfigurationSection rankDataSection = rankDataConfig.getConfigurationSection(rankId);
            if (null == rankDataSection) {
                plugin.getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                        ColorUtil.color(String.format("&c加载排行榜持久化数据失败：%s", rankId)));
                return;
            }
            String rankDataId = rankDataSection.getString("rank-id", rankId);
            boolean isEnd = rankDataSection.getBoolean("is-end");
            String updateDateTime = rankDataSection.getString("update-date-time");
            rankData = new RankData(rankDataId, isEnd, DateUtil.strFormatDate(updateDateTime));
        }
        rankDataMap.put(rankId, rankData);
    }


    /**
     * 创建rankdata.yml
     */
    public void createRankDataFile() {
        plugin.saveResource(StaticSystemVarConst.RANK_DATA_DEFAULT_NAME, false);
    }

    /**
     * 获取rankdata.yml配置对象
     * @return
     */
    private YamlConfiguration getRankDataConfig() {
        if(! RANK_DATE_FILE.exists()) {
            createRankDataFile();
        }
        return YamlConfiguration.loadConfiguration(RANK_DATE_FILE);
    }

}
